package com.graduation.system.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import cn.circle.commom.controller.BackendBaseController;
import cn.circle.system.util.DataGrid;
import com.graduation.system.model.SysCustomer;
import com.graduation.system.model.SysDepartment;
import cn.circle.system.service.ISysDepartmentService;
import cn.circle.system.util.ReturnInfo;
import cn.circle.system.util.ConfigProperty;
import cn.circle.system.util.FileUploadUtil;

@Controller
@RequestMapping("/manage/sysDepartment")
public class SysDepartmentController extends BackendBaseController{

	private static final Log log = LogFactory.getLog(SysDepartmentController.class);
	
	@Autowired
	private ISysDepartmentService sysDepartmentService;
	
	/**
	 * 跳转到Department首页
	 */
	@RequestMapping(value = "/index")
	public String sysDepartmentIndex() {
		return "/WEB-INF/jsp/system/system/Department/sys_department_list.jsp";
	}
	/**
	 * 跳转到Department增加页
	 */
	@RequestMapping(value = "/add")
	public String add(Map<String, Object> map) {
		log.info("----Ok----");
		map.put("saveUrl", "/manage/sysDepartment/addSave");
		return "/WEB-INF/jsp/system/system/Department/sys_department_au.jsp";
	}
	
	/**
	 * 跳转到Department回收站
	 */
	@RequestMapping(value = "/toDataGridBack")
	public String toDataGridBack(Map<String, Object> map) {
		log.info("----Ok----");
		map.put("saveUrl", "/manage/sysDepartment/dataGridBack");
		return "/WEB-INF/jsp/system/system/Department/sys_department_back.jsp";
	}

	/**
	 * 跳转至 sysdepartment_au页
	 */
	@RequestMapping(value = "/edit")
	public String edit(String depId, Map<String, Object> map) {
		log.info(depId);
		map.put("saveUrl", "/manage/sysDepartment/editSave");
		if (depId != null) {
			List<SysDepartment> model = sysDepartmentService.getUser(depId);
			log.info(model.get(0));
			map.put("model", model.get(0));
		}
		return "/WEB-INF/jsp/system/system/Department/sys_department_au.jsp";
	}
	/**
	 * 查询客户信息
	 */
	@ResponseBody
	@RequestMapping(value = "/dataGrid")
	public DataGrid dataGrid() {
		DataGrid dg = sysDepartmentService.datagrid();
		return dg;
	}
	/**
	 * 查询回收站信息
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/dataGridBack")
	public DataGrid dataGridBack(DataGrid dg) {
		//DataGrid dg = sysDepartmentService.datagrid();
		// TODO Auto-generated method stub
		String hql = "from SysDepartment s where s.status = 1";
		Query query = super.sessionFactory.getCurrentSession().createQuery(hql);
		List<SysDepartment> l = query.list();
		dg.setTotal((long)l.size());
		dg.setRows(l);
		System.out.println("opopopopop");
		return dg;
	}
	/**
	 * 保存修改对数据
	 */
	@ResponseBody
	@RequestMapping(value = "/editSave")
	public ReturnInfo editSave(@Valid SysDepartment sysDepartment, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		} else {
			if(file != null){
				try {
					String icon_url = FileUploadUtil.saveFile(file, request, ConfigProperty.getProperty("fileUplaodPath", "config") + "icon");
					sysDepartment.setDepIcon(icon_url);
					if (sysDepartment != null) {
						try {
							sysDepartmentService.update(sysDepartment);
						} catch (Exception e) {
							log.info("保存失败" + e.getMessage());
							result.setMsg("保存失败！");
							result.setSuccess(1);
						}
					}
				} catch (Exception e) {
					log.info("上传异常"+e.getMessage());
					result.setMsg("上传文件异常，保存失败！");
					result.setSuccess(1);
				}
			}
		}

		return result;
	}
	/**
	 * 保存添加数据
	 */
	@ResponseBody
	@RequestMapping(value = "/addSave")
	public ReturnInfo addSave(@Valid SysDepartment sysDepartment, BindingResult b, ReturnInfo result, @RequestParam(value = "uploadFile", required = false) MultipartFile file, HttpServletRequest request) {
		if (b.getErrorCount() > 0) { // 数据校验
			for (FieldError error : b.getFieldErrors()) {
				log.info(error.getField() + ":" + error.getDefaultMessage());
				result.setMsg(error.getDefaultMessage());
			}
			result.setSuccess(1);
		}else {
			if(file != null){
				try {
					String icon_url = FileUploadUtil.saveFile(file, request, ConfigProperty.getProperty("fileUplaodPath", "config") + "icon");
					sysDepartment.setDepIcon(icon_url);
					if (sysDepartment != null) {
						try {
							sysDepartmentService.save(sysDepartment);
						} catch (Exception e) {
							log.info("保存失败" + e.getMessage());
							result.setMsg("保存失败！");
							result.setSuccess(1);
						}
					}
				} catch (Exception e) {
					log.info("上传异常"+e.getMessage());
					result.setMsg("上传文件异常，保存失败！");
					result.setSuccess(1);
				}
			}
			
		}

		return result;
	}
	/**
	 * 改变状态status
	 */
	@ResponseBody
	@RequestMapping(value = "/remove")
	public ReturnInfo remove(String depIds, ReturnInfo result) {
		
		sysDepartmentService.remove(depIds);
		System.out.println("1");
		return result;
	}
	/**
	 * 改变状态status为正常
	 */
	@ResponseBody
	@RequestMapping(value = "/back")
	public ReturnInfo back(String depIds, ReturnInfo result, Map<String, Object> map) {
		map.put("saveUrl", "/manage/sysDepartment/index");
		sysDepartmentService.back(depIds);
		return result;
	}
	/**
	 * 删除若干条数据
	 */
	@ResponseBody
	@RequestMapping(value = "/delete")
	public ReturnInfo delete(String depIds, ReturnInfo result) {
		sysDepartmentService.delete(depIds);
		return result;
	}
	/**
	 * 获得客户详细资料
	 */
	@RequestMapping(value = "/queryDepDetail")
	public String queryCustDetail(String depId, Map<String, Object> map) {
		log.info(depId);
		if (depId != null) {
			List<SysDepartment> model = sysDepartmentService.getUser(depId);
			map.put("model", model.get(0));
		}
		return "/WEB-INF/jsp/system/system/Department/sys_department_detail.jsp";
	}
}
